package com.example.musicaiap.data.repository

import android.content.Context
import android.util.Log
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject
import javax.inject.Singleton

/**
 * 收藏状态仓库
 * 
 * 作为单一真实数据源管理收藏状态，并在状态变更时通知观察者
 * 使用Flow机制进行状态同步
 */
@Singleton
class FavoriteStateRepository @Inject constructor(
    private val context: Context
) {
    companion object {
        // 日志标签
        private const val TAG = "FavoriteStateRepo"
    }
    
    // 使用Map存储所有歌曲的收藏状态
    private val favoriteStates = mutableMapOf<String, Boolean>()
    
    // 当前选中歌曲的收藏状态
    private val _currentFavoriteState = MutableStateFlow(false)
    val currentFavoriteState: StateFlow<Boolean> = _currentFavoriteState.asStateFlow()
    
    // 当前选中的歌曲ID
    private val _currentSongId = MutableStateFlow("")
    val currentSongId: StateFlow<String> = _currentSongId.asStateFlow()
    
    // 创建收藏状态变更的SharedFlow，替代广播
    data class FavoriteChangeEvent(val songId: String, val isFavorite: Boolean)
    private val _favoriteChanges = MutableSharedFlow<FavoriteChangeEvent>(extraBufferCapacity = 10)
    val favoriteChanges: SharedFlow<FavoriteChangeEvent> = _favoriteChanges.asSharedFlow()
    
    /**
     * 获取歌曲的收藏状态
     */
    fun getSongFavoriteState(songId: String): Boolean {
        return favoriteStates[songId] ?: false
    }
    
    /**
     * 设置歌曲的收藏状态
     * 发送Flow事件以通知所有观察者
     */
    fun setSongFavoriteState(songId: String, isFavorite: Boolean) {
        Log.d(TAG, "设置歌曲 $songId 的收藏状态为 $isFavorite")
        
        // 更新内存中的状态
        favoriteStates[songId] = isFavorite
        
        // 如果是当前选中的歌曲，更新当前状态Flow
        if (songId == _currentSongId.value) {
            _currentFavoriteState.value = isFavorite
        }
        
        // 发送状态变更事件到SharedFlow
        _favoriteChanges.tryEmit(FavoriteChangeEvent(songId, isFavorite))
    }
    
    /**
     * 设置当前选中的歌曲
     */
    fun setCurrentSong(songId: String) {
        _currentSongId.value = songId
        
        // 更新当前歌曲的收藏状态Flow
        _currentFavoriteState.value = favoriteStates[songId] ?: false
        
        Log.d(TAG, "设置当前歌曲 $songId，收藏状态 ${_currentFavoriteState.value}")
    }
    
    /**
     * 初始化歌曲的收藏状态
     * 从数据库加载后调用此方法
     */
    fun initSongFavoriteState(songId: String, isFavorite: Boolean) {
        favoriteStates[songId] = isFavorite
        
        // 如果是当前选中的歌曲，更新当前状态
        if (songId == _currentSongId.value) {
            _currentFavoriteState.value = isFavorite
        }
    }
} 